package com.yipao.wx.service;

import com.yipao.core.constant.GlobalConstant;
import com.yipao.db.domain.user.User;
import com.yipao.db.service.user.UserService;
import com.yipao.wx.dto.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 用户
 *
 * @author tianhao
 */
@Service
public class UserInfoService {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public UserInfo getInfo(Integer userId) {
        User user = userService.findById(userId);
        Assert.state(user != null, "用户不存在");
        UserInfo userInfo = new UserInfo();
        userInfo.setNickName(user.getNickname());
        userInfo.setAvatarUrl(user.getAvatar());
        userInfo.setMobile(user.getMobile());
        return userInfo;
    }

    /**
     * 获取用户绑定的设备id
     *
     * @param userId
     * @return
     */
    public Integer getDevId(Integer userId) {
        String devId = redisTemplate.opsForValue().get(GlobalConstant.RedisKeyConstant.USER_INFO_DEV_ID_PREFIX);
        if (StringUtils.isBlank(devId)) {
            devId = userService.findDevIdById(userId).toString();
            Assert.state(devId != null, "用户未绑定设备");
            redisTemplate.opsForValue().set(GlobalConstant.RedisKeyConstant.USER_INFO_DEV_ID_PREFIX, devId, 1, TimeUnit.DAYS);
        }
        return Integer.valueOf(devId);
    }

    /**
     * 获取用户的手机号码
     * @param userId 用户id
     * @return
     */
    public String getMobile(Integer userId) {
        return userService.findMobileById(userId);
    }
}
